package com.nacos.shangtu.service.impl;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.nacos.shangtu.entity.dto.ConversationDto;
import com.nacos.shangtu.entity.dto.MessageDto;
import com.nacos.shangtu.entity.po.GroupUserPO;
import com.nacos.shangtu.entity.po.MessagePO;
import com.nacos.shangtu.entity.po.RecordPO;
import com.nacos.shangtu.mapper.GroupUserMapper;
import com.nacos.shangtu.mapper.MessageMapper;
import com.nacos.shangtu.mapper.RecordMapper;
import com.nacos.shangtu.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private GroupUserMapper groupUserMapper;

    @Autowired
    private RecordMapper recordMapper;

    @Override
    public List<MessageDto> getMessageList(String groupId) {
        return messageMapper.getMessageList(groupId);
    }

    @Override
    public void save(MessagePO chatMessage) {
        messageMapper.insert(chatMessage);
    }

    @Override
    public List<ConversationDto> getConversions(String userId) {
        List<ConversationDto> conversationDtos = new ArrayList<>();
        List<GroupUserPO> groupUserPOS = groupUserMapper.selectByUserId(userId);
        for (GroupUserPO groupUserPO : groupUserPOS) {
            conversationDtos.addAll(messageMapper.findConversations(groupUserPO.getGroupId()));
        }
        return conversationDtos;
    }

    @Override
    public List<MessageDto> findNotSendMessages(String userId, @Nullable boolean update) {
        List<RecordPO> records = recordMapper.findByUserIdAndStatus(userId, 0); // 未发送
        List<String> messageIds = records.stream().map(RecordPO::getMessageId).collect(Collectors.toList());
        List<List<String>> partitions = Lists.partition(messageIds, 20);
        List<MessageDto> messageDtos = partitions.stream()
                .flatMap(o -> messageMapper.getMessageByIds(o).stream()).collect(Collectors.toList());

        if (update) {
            // 更新为已发送
            List<String> ids = records.stream().map(RecordPO::getId).collect(Collectors.toList());
            List<List<String>> partitions2 = Lists.partition(ids, 20);
            for (List<String> ids2 : partitions2) {
                recordMapper.updateRecords(ids2, 1);
            }
            log.info("update record, size - {}.", ids.size());
        }
        return messageDtos;
    }
}
